package CommonGui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Rectangle;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;


public class AutoScaledPainter extends ImagePainter
{	
	private static final long serialVersionUID = 1L;

	public AutoScaledPainter(Image image) {
		super(image); 
		this.image = image;
	}
	
	// Draw image, implements Printable interface
	public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException 
	{
		if (pageIndex > 0)
			return Printable.NO_SUCH_PAGE;
		
		Graphics2D g2D = (Graphics2D) g;
		g2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

		g2D.setPaint(Color.black);
		
		MediaTracker mt = new MediaTracker(this); 
	    mt.addImage(image, 0);
	    try {
	    	mt.waitForID(0);
	    	} catch (InterruptedException e) {
	    	}
		
	    double x = pageFormat.getImageableX();
	    	
	    Rectangle drawRect = getDrawRect(pageFormat);
		if ( g2D.drawImage(image,
				drawRect.x, 
				drawRect.y,
				drawRect.width,
				drawRect.height,
				null // Doesn't not wait for asynchronous operation
				) == false )
		{
			return NO_SUCH_PAGE;
		}
		
		return Printable.PAGE_EXISTS;
	}
}